package org.xfy.ymcc.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.xfy.common.constant.RConst;
import org.xfy.common.result.JsonResult;
import org.xfy.ymcc.domain.*;
import org.xfy.ymcc.dto.AddCourseDto;
import org.xfy.ymcc.feign.MediaFeignClient;
import org.xfy.ymcc.feign.SearchFeignClient;
import org.xfy.ymcc.mapper.CourseDetailMapper;
import org.xfy.ymcc.mapper.CourseMapper;
import org.xfy.ymcc.mapper.TeacherMapper;
import org.xfy.ymcc.producer.CourseProducer;
import org.xfy.ymcc.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.xfy.ymcc.vo.GetDetailDataVo;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author xfy
 * @since 2023-12-01
 */
@Service
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements ICourseService {
    @Autowired
    private TeacherMapper teacherMapper;
    @Autowired
    private CourseMapper courseMapper;
    @Autowired
    private ICourseDetailService courseDetailService;
    @Autowired
    private ICourseResourceService courseResourceService;
    @Autowired
    private ICourseMarketService courseMarketService;
    @Autowired
    private ICourseSummaryService courseSummaryService;
    @Autowired
    private ICourseTypeService courseTypeService;
    @Autowired
    private ICourseCollectService courseCollectService;
    @Autowired
    private SearchFeignClient searchFeignClient;
    @Autowired
    private CourseProducer courseProducer;
    @Autowired
    private ICourseChapterService courseChapterService;
    @Autowired
    private MediaFeignClient mediaFeignClient;

    @Override
    public void save(AddCourseDto addCourseDto, Long id, String username) {
        //保存信息
        //保存主标信息
        Long courseId = saveCourse(addCourseDto, id, username);
        //保存详情信息
        saveCourseDetail(addCourseDto, courseId);
        //保存资源表
        saveCourseResource(addCourseDto, courseId);
        //保存市场表
        saveCourseMarket(addCourseDto, courseId);
        //保存访问表,初始化
        saveCourseSummary(courseId);

    }

    @Override
    public JsonResult getEdit(Long id) {
        AddCourseDto addCourseDto = new AddCourseDto();
        addCourseDto.setCourse(courseMapper.selectOne(new LambdaQueryWrapper<Course>()
                .eq(Course::getId, id)));
        addCourseDto.setCourseDetail(courseDetailService.getOne(new LambdaQueryWrapper<CourseDetail>()
                .eq(CourseDetail::getId, id)));
        addCourseDto.setCourseMarket(courseMarketService.getOne(new LambdaQueryWrapper<CourseMarket>()
                .eq(CourseMarket::getId, id)));
        addCourseDto.setCourseResource(courseResourceService.getOne(new LambdaQueryWrapper<CourseResource>()
                .eq(CourseResource::getCourseId, id)));
        List<Long> TeacherIDs = courseMapper.selectTeacherIDs(id);
        addCourseDto.setTeacharIds(TeacherIDs);
        return JsonResult.success().setData(addCourseDto);
    }

    @Override
    public JsonResult onLineCourse(List<Long> courseIds) {
        //查询那些课程需要上线
        LambdaQueryWrapper<Course> wrapper = new LambdaQueryWrapper<Course>()
                .eq(Course::getStatus, RConst.Num.INT_0)
                .in(Course::getId, courseIds);
        List<Course> courses = super.baseMapper.selectList(wrapper);
        //将查询出的课程更改状态
        courses.forEach(item -> {
            item.setStatus(1);
            item.setOnlineTime(new Date());
            //添加到es
            CourseDoc courseDoc = buildCourseDoc(item);
            // System.out.println(courseDoc.toString());
            //发送MQ消息通知
            // 已经收藏的人 需要的内容
            List<CourseCollect> list = courseCollectService.list(
                    new LambdaQueryWrapper<CourseCollect>().eq(CourseCollect::getCourseId, item.getId()));
            for (CourseCollect courseCollect : list) {
                HashMap<String, Object> map = new HashMap<>();
                map.put("id",courseCollect.getUserId());
                map.put("content",item.getName()+"已上架，亲可以去购买观看");
                courseProducer.sendSMSProducer(JSON.toJSONString(map));
                courseProducer.sendEmailProducer(JSON.toJSONString(map));
            }
            searchFeignClient.saveSearch(courseDoc);
            super.baseMapper.updateById(item);
        });
        return JsonResult.success();
    }

    @Override
    public JsonResult getDetailData(Long courseId) {
        //1.从ES里面去查数据然后封装

        //2.从数据库中查询
        GetDetailDataVo getDetailDataVo = new GetDetailDataVo();
        getDetailDataVo.setCourse(super.getById(courseId));
        getDetailDataVo.setCourseDetail(courseDetailService.getById(courseId));
        getDetailDataVo.setCourseMarket(courseMarketService.getById(courseId));
        getDetailDataVo.setCourseSummary(courseSummaryService.getById(courseId));
        List<CourseChapter> CourseChapterlist = courseChapterService
                .list(new LambdaQueryWrapper<CourseChapter>().eq(CourseChapter::getCourseId, courseId));
        for (CourseChapter courseChapter : CourseChapterlist) {
            Long id = courseChapter.getId();
            //调用Media接口去查询章节
            JsonResult mediaFileByChapterId = mediaFeignClient.getMediaFileByChapterId(id);
            String jsonString = JSON.toJSONString(mediaFileByChapterId.getData());
            List<MediaFile> mediaFiles = JSON.parseArray(jsonString, MediaFile.class);
            courseChapter.setMediaFiles(mediaFiles);
        }
        /*CourseChapterlist.forEach(courseChapter -> {

        });*/

        getDetailDataVo.setCourseChapters(CourseChapterlist);
        //添加老师的数据
        List<Long> longs = courseMapper.selectTeacherIDs(courseId);
        getDetailDataVo.setTeachers(teacherMapper.selectBatchIds(longs));
        return JsonResult.success().setData(getDetailDataVo);
    }

    private CourseDoc buildCourseDoc(Course item) {
        CourseDoc courseDoc = new CourseDoc();
        BeanUtils.copyProperties(item, courseDoc);
        CourseType byId = courseTypeService.getById(item.getCourseTypeId());
        courseDoc.setCourseTypeName(byId.getName());

        courseDoc.setStartTime(item.getStartTime().getTime());
        courseDoc.setEndTime(item.getEndTime().getTime());

        courseDoc.setOnlineTime(item.getOnlineTime().getTime());
        //详情
        CourseDetail detail = courseDetailService.getById(item.getId());
        BeanUtils.copyProperties(detail, courseDoc);
        //收费规则
        CourseMarket market = courseMarketService.getById(item.getId());
        BeanUtils.copyProperties(market, courseDoc);
        courseDoc.setPrice(market.getPrice().doubleValue());
        courseDoc.setPriceOld(market.getPriceOld().doubleValue());
        //销量
        CourseSummary summary = courseSummaryService.getById(item.getId());
        if (summary != null) {
            BeanUtils.copyProperties(summary, courseDoc);
        }
        //收藏
        int count = courseCollectService.count(new LambdaQueryWrapper<CourseCollect>().eq(CourseCollect::getCourseId, item.getId()));
        courseDoc.setCollectCount(count);

        return courseDoc;
    }

    private void saveCourseMarket(AddCourseDto addCourseDto, Long courseId) {
        CourseMarket courseMarket = new CourseMarket();
        BeanUtils.copyProperties(addCourseDto.getCourseMarket(), courseMarket);
        courseMarket.setId(courseId);
        courseMarketService.saveOrUpdate(courseMarket);
    }

    private void saveCourseSummary(Long courseId) {
        CourseSummary courseSummary = new CourseSummary();
        courseSummary.setId(courseId);
        courseSummary.setCommentCount(RConst.Num.INT_0);
        courseSummary.setSaleCount(RConst.Num.INT_0);
        courseSummary.setViewCount(RConst.Num.INT_0);
        courseSummaryService.save(courseSummary);
    }

    private void saveCourseResource(AddCourseDto addCourseDto, Long courseId) {
        CourseResource courseResource = new CourseResource();
        BeanUtils.copyProperties(addCourseDto.getCourseResource(), courseResource);
        courseResource.setCourseId(courseId);
        courseResourceService.saveOrUpdate(courseResource);
    }

    private void saveCourseDetail(AddCourseDto addCourseDto, Long courseId) {
        CourseDetail courseDetail = new CourseDetail();
        BeanUtils.copyProperties(addCourseDto.getCourseDetail(), courseDetail);
        courseDetail.setId(courseId);
        courseDetailService.saveOrUpdate(courseDetail);
    }

    private Long saveCourse(AddCourseDto addCourseDto, Long id, String username) {
        Course course = new Course();
        BeanUtils.copyProperties(addCourseDto.getCourse(), course);
        course.setLoginId(id);
        course.setLoginUserName(username);
        course.setStatus(RConst.Num.INT_0);
        course.setTotalMinute(RConst.Num.INT_0);
        course.setChapterCount(RConst.Num.INT_0);
        //保存教姓名
        List<Long> teacharIds = addCourseDto.getTeacharIds();
        List<Teacher> teachers = teacherMapper.selectBatchIds(teacharIds);
        List<String> collect = teachers.stream().map(Teacher::getName).collect(Collectors.toList());
        course.setTeacherNames(String.join(",", collect));
        super.saveOrUpdate(course);
        courseMapper.deleteTeacherRelationship(course.getId());
        //保存教师中间表
        courseMapper.saveTeacherRelationship(addCourseDto.getTeacharIds(), course.getId());
        return course.getId();
    }

    @Override
    public void updateById(AddCourseDto addCourseDto, Long id, String username) {
        //保存信息
        //保存主标信息
        Long courseId = saveCourse(addCourseDto, id, username);
        //保存详情信息
        saveCourseDetail(addCourseDto, courseId);
        //保存资源表
        saveCourseResource(addCourseDto, courseId);
        //保存市场表
        saveCourseMarket(addCourseDto, courseId);
    }
}
